package com.cqcetbbs.smartlab.cqcetbbs.activity;


import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;

import com.cqcetbbs.smartlab.cqcetbbs.R;
import com.cqcetbbs.smartlab.cqcetbbs.adapter.CommentAdapter;
import com.cqcetbbs.smartlab.cqcetbbs.javabean.NewsDetailArt;
import com.cqcetbbs.smartlab.cqcetbbs.javabean.ReplyInfos;
import com.cqcetbbs.smartlab.cqcetbbs.utils.SpUtils;
import com.cqcetbbs.smartlab.cqcetbbs.view.CommomDialog;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

import cn.sharesdk.onekeyshare.OnekeyShare;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by user on 2017/10/5.
 * <p>
 * 发现详情页面
 */

public class NewsDetailActivity extends Activity {

    //发现发现详情页面数据key
    public static final String NDA_DATA = "NewsDetailActivity_data";
    //显示回复
    public static final String SHOW_REPLY_PATH = "http://api.cqcetlab.com/Home/article/showReply";

    //回复
    public static final String REPLY_PATH = "http://api.cqcetlab.com/Home/article/Reply";

    public static final int ART_DATA = 1;
    public static final int ART_FAIL = 2;
    public static final int REPLY_SUCCESS = 3;
    public static final int REPLY_FAIL = 4;
    public static final int UP_REPLY_SUCCESS = 5;
    public static final int UP_REPLY_FAIL = 6;


    private WebView wv_content;
    private Toolbar tb_title;
    private EditText et_content;
    private Button btn_comment;
    private ImageView iv_back;
    private ListView lv_comment;
    private NewsDetailArt mNewsDetailArt;
    private TextView tv_title;
    private ImageView iv_share;
    CommentAdapter CommentAdapter;
    private ArrayList<String> commentLists;
    LinearLayout ll_not_net;
    //文章id
    private String Art_id;
    private Gson gson;

    int page = 1;

    OkHttpClient client = new OkHttpClient();


    Handler mhander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ART_DATA:
                    if (!TextUtils.isEmpty((String) msg.obj)) {
                        gson = new Gson();
                        mNewsDetailArt = gson.fromJson((String) msg.obj, NewsDetailArt.class);
                        ininData();
                    }
                    break;
                case ART_FAIL:
                    wv_content.setVisibility(View.GONE);
                    ll_not_net.setVisibility(View.VISIBLE);
                    break;
                case REPLY_SUCCESS:
                    if (null == gson) {
                        gson = new Gson();
                    }
                    ReplyInfos ReplyInfos = gson.fromJson((String) msg.obj, ReplyInfos.class);
                    CommentAdapter = new CommentAdapter(NewsDetailActivity.this, ReplyInfos.getData());
                    lv_comment.setAdapter(CommentAdapter);
                    if (ReplyInfos.getCount().equals("0")) {
                        lv_comment.setAdapter(new ArrayAdapter<String>(NewsDetailActivity.this, R.layout.lv_comment_item, R.id.tv_content, new String[]{"暂无评论"}));
                    }

                    CommentAdapter.setonDeletedLisenter(new CommentAdapter.onDeletedLisenter() {
                        @Override
                        public void onDeleted() {
                            new CommomDialog(NewsDetailActivity.this, 0, "您确定删除此信息？", new CommomDialog.OnCloseListener() {
                                //
                                @Override
                                public void onClick(Dialog dialog, boolean confirm) {
                                    if (confirm) {

                                        //从服务器中删除


                                        dialog.dismiss();
                                    }
                                }
                            }).setTitle("提示").show();
                        }
                    });

                    CommentAdapter.onReplyAndReplyLisenter(new CommentAdapter.onReplyAndReplyLisenter() {
                        @Override
                        public void ReplyAndReply(){
                        }
                    });

                    break;
                case REPLY_FAIL:
                    break;
                case UP_REPLY_FAIL:
                    break;
                case UP_REPLY_SUCCESS:
                    Toast.makeText(getApplicationContext(), "回复成功！", Toast.LENGTH_SHORT).show();
                    getReplyData(Art_id, "20", "1");
                    break;
            }

        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_newsdetail);
        ll_not_net = findViewById(R.id.ll_not_net);
        ll_not_net.setVisibility(View.GONE);
        Bundle bundle = getIntent().getExtras();
        Art_id = bundle.getString("id");
        initView();
        getData(Art_id);
        getReplyData(Art_id, "20", "1");
    }

    private void ininData() {
        tv_title.setText(mNewsDetailArt.getTitle());
        wv_content.loadUrl("http://api.cqcetlab.com/Home/article/?id=" + mNewsDetailArt.getId());
        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        wv_content.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO Auto-generated method stub
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                view.loadUrl(url);
                return true;
            }
        });

        btn_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String content = null;
                content = et_content.getText().toString();
                if (TextUtils.isEmpty(content)) {
                    Toast.makeText(getApplicationContext(), "评论不能为空！", Toast.LENGTH_SHORT).show();
                    return;
                }
                Random random = new Random(100000);
                int i = random.nextInt();

                upReplyInfos(Art_id, String.valueOf(i), content, "");


                //将输入法隐藏，mPasswordEditText 代表密码输入框
                InputMethodManager imm = (InputMethodManager) getSystemService(
                        Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(et_content.getWindowToken(), 0);

                lv_comment.setSelection(0);
                et_content.setText("");
            }
        });


        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        iv_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //分享应用
                showShare();
            }
        });
    }

    private void initView() {
        commentLists = new ArrayList<>();
        lv_comment = findViewById(R.id.lv_comment);

        iv_back = findViewById(R.id.iv_back);
        iv_share = findViewById(R.id.iv_share);
        wv_content = findViewById(R.id.wv_content);

        et_content = findViewById(R.id.et_content);
        btn_comment = findViewById(R.id.btn_comment);
        tv_title = findViewById(R.id.tv_title);

        //将数据取出，用于离线展示
        String result = SpUtils.getStringValues(NewsDetailActivity.this, NDA_DATA, null);
        Message msg = mhander.obtainMessage(ART_DATA, result);
        mhander.sendMessage(msg);

    }

    //将回复的信息上传到服务器
    public void upReplyInfos(String article_id, String user_id, String reply_content, String reply_pic) {
        final String inner_article_id = article_id;
        final String inner_user_id = user_id;
        final String inner_reply_content = reply_content;
        final String inner_reply_pic = reply_pic;
        final OkHttpClient httpClient = new OkHttpClient();
        new Thread(new Runnable() {
            @Override
            public void run() {

                RequestBody body = new FormBody.Builder()
                        .add("user_id", inner_user_id)
                        .add("reply_content", inner_reply_content)
                        .add("reply_pic", inner_reply_pic)
                        .add("article_id", inner_article_id)
                        .build();
                Request request = new Request.Builder()
                        .url(REPLY_PATH)
                        .get()
                        .put(body).build();
                Response response = null;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String result = response.body().string();
                        Message msg = mhander.obtainMessage(UP_REPLY_SUCCESS, result);
                        mhander.sendMessage(msg);
                    } else {
                        Message msg = mhander.obtainMessage(UP_REPLY_FAIL);
                        mhander.sendMessage(msg);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }


    //显示回帖的内容
    public void getReplyData(String article_id, String num, String page) {
        final String inner_article_id = article_id;
        final String inner_num = num;
        final String inner_page = page;
        Log.e("getReplyData", inner_article_id);
        final OkHttpClient httpClient = new OkHttpClient();
        new Thread(new Runnable() {
            @Override
            public void run() {

                RequestBody body = new FormBody.Builder()
                        .add("article_id", inner_article_id)
                        .add("num", inner_num)
                        .add("page", inner_page)
                        .build();
                Request request = new Request.Builder()
                        .url(SHOW_REPLY_PATH)
                        .get()
                        .put(body).build();
                Response response = null;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String result = response.body().string();
                        Message msg = mhander.obtainMessage(REPLY_SUCCESS, result);
                        mhander.sendMessage(msg);
                    } else {
                        Message msg = mhander.obtainMessage(REPLY_FAIL);
                        mhander.sendMessage(msg);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }


    // get请求后台数据
    private void getData(final String id) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                Request request = new Request.Builder()
                        .get()
                        .url("http://api.cqcetlab.com/Home/article/artinfo?id=" + id)
                        .build();

                //新建一个线程，用于得到服务器响应的参数
                Response response = null;
                try {
                    //回调
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                        String result = response.body().string();
                        //将数据保存
                        SpUtils.setStringValues(NewsDetailActivity.this, NDA_DATA, result);
                        Message msg = mhander.obtainMessage(ART_DATA, result);
                        mhander.sendMessage(msg);
                    } else {
                    }
                } catch (IOException e) {
                    Message msg = mhander.obtainMessage(ART_FAIL);
                    mhander.sendMessage(msg);
                    e.printStackTrace();
                }
            }
        }).start();


    }


    private void showShare() {
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

        // 分享时Notification的图标和文字  2.5.9以后的版本不     调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle("重电论坛");
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://api.cqcetlab.com/Home/article/?id=" + mNewsDetailArt.getId());
        // text是分享文本，所有平台都需要这个字段
        oks.setText("重电精美文章" + "http://api.cqcetlab.com/Home/article/?id=" + mNewsDetailArt.getId());
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://api.cqcetlab.com/Home/article/?id=" + mNewsDetailArt.getId());
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("重电精美文章");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://api.cqcetlab.com/Home/article/?id=" + mNewsDetailArt.getId());

        // 启动分享GUI
        oks.show(this);
    }
}
